const baseRequest=require("./baseRequest")
const config=require("./config")
const comon=require("./common")
/**
 * 获取jwt密匙
 * @return {Promise<string>}
 */
const getJwtPayload=async()=>{
  let jwtPayload= wx.getStorageSync('jwtPayload')
  if (jwtPayload == undefined || jwtPayload=="") {
    return new Promise((resolve,reject)=>{
      wx.login({
      }).then((res)=>{
        console.log("微信登录 code",res.code)
        baseRequest.loginRequest("wxv2","login",{appId:config.appId,code:res.code})
          .then(
            (res)=>{
              console.log("服务器下发登录信息",res)
              if(res.jwtPayload){
                wx.setStorageSync('jwtPayload',res.jwtPayload);
              }
              resolve(res.jwtPayload)
            },
           err=>{
            console.error("服务器下发登录信息失败",err)
             wx.clearStorageSync()
            reject(err)
           })
      },
      err=>{
        wx.clearStorageSync()
        reject(err)
      })
    })
  }else{
    const jwt=jwtPayload.split(".");
    const arrayBuffer =wx.base64ToArrayBuffer(jwt[1])
    const json=String.fromCharCode.apply(null,new Uint8Array(arrayBuffer))
    // console.log(json)
    const {exp}=JSON.parse(json)
    if (exp>Date.now()/1000){
      console.log("token有效使用原来token")
      return Promise.resolve(jwtPayload)
    }else{
      console.warn("token无效重新获取token")
      wx.clearStorageSync()
      return getJwtPayload()
    }
  }
}
/**
 * 获取用户OpenId
 */
const getOpenId=async()=>{
  return new Promise((resolve,reject)=>{
    getJwtPayload().then(success=>{
      console.log("获取OpenId成功")
      const split=success.split(".")
      const arrayBuffer =wx.base64ToArrayBuffer(split[1])
      const json=String.fromCharCode.apply(null,new Uint8Array(arrayBuffer))
      const {openId}=JSON.parse(json)
      resolve({openId})
    },err=>{
      reject(err)
      console.error(err)
    })
  })
  
}
module.exports={
  getJwtPayload,
  getOpenId
}
